package com.dkm.orproject.dkmoa.action.flow;

import com.alibaba.fastjson.JSON;
import com.dkm.orproject.dkmoa.domain.OaDimissionFlow;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.service.flow.OaDimissionFlowService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.Tools;
import io.swagger.annotations.*;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName : OaDimissionFlowAction  //类名
 * @Description : 员工离职Action  //描述
 * @Author : 易嵘  //作者
 * @Date: 2020-08-14 10:42  //时间
 */
@RestController
@RequestMapping("OaDimissionFlowAction")
public class
OaDimissionFlowAction {

    /**
     * 员工离职服务接口
     */
    @Resource
    OaDimissionFlowService dimissionFlowService;

    /**
     * 前台传值工具类
     */
    @Resource
    Tools tools;

    /**
     * 回调值
     */
    int row=0;

    /**
     * 日志
     */
    OaLog log;

    /**
     * 登陆人
     */
    OaPersonnel personnel;

    /**
     * 回调map
     */
    Map<String,Object> map;

    /**
     * 分页查询
     * @param dimissionFlow 离职流程模型
     * @param page 当前页数
     * @param limit 显示行数
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @param request 服务器请求 用于得到登陆人信息
     * @return 模型集
     */
    @ApiOperation(value = "员工离职分页查询接口", notes = "员工离职分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "demissionName",value = "离职流程名称（模糊）",dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name = "limit", value = "显示行数", required = true, dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header"),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaDimissionFlow.class),
    })
    @UserLoginToken
    @GetMapping("findAll")
    public Map<String,Object> findAll(OaDimissionFlow dimissionFlow,
                                      Integer page,
                                      Integer limit,
                                      String startDate,
                                      String endDate,
                                      HttpServletRequest request){
        try{
            List<OaDimissionFlow> list=dimissionFlowService.findAll(dimissionFlow,page,limit,startDate,endDate);
            Long rowCount=dimissionFlowService.rowCount(dimissionFlow,startDate,endDate);
            return Tools.maps(list,rowCount);
        }catch (Exception e){
            addErrorLog(request,"人员离职流程分页查询",e);
        }
        return null;
    }

    @UserLoginToken
    @DeleteMapping("deleteAll")
    public int deleteAll(@RequestParam(value = "ids[]",required = false) Long[] ids,HttpServletRequest request){
        List<Long> list= Arrays.asList(ids);
        return dimissionFlowService.deleteAll(list);
    }

    /**
     * 起草节点
     * @param dimissionFlow 离职流程模型
     * @param request 服务器请求 用于得到登陆人信息
     * @return 回调函数
     */
    @UserLoginToken
    @PostMapping("addDimissionFlow")
    public int addDimissionFlow(OaDimissionFlow dimissionFlow,HttpServletRequest request){
        rowMap(request);
        try{
            return dimissionFlowService.add(dimissionFlow,personnel);
        }catch (Exception e){
            addErrorLog(request,"人员离职起草节点",e);
            return 500;
        }
    }

    /**
     * 部门领导通过
     * @param pkDimissionId 离职流程模型
     * @param request 服务器请求 用于得到登陆人信息
     * @return
     */
    @UserLoginToken
    @PostMapping("sectionPass")
    public int sectionPass(@RequestParam("pkDimissionId") Long pkDimissionId,HttpServletRequest request,@RequestParam("departmentLeadership") String departmentLeadership){
        rowMap(request);
        try{
            return dimissionFlowService.sectionPass(pkDimissionId,personnel,departmentLeadership);
        }catch (Exception e){
            addErrorLog(request,"部门领导通过",e);
            return 500;
        }
    }

    /**
     * 部门领导不通过
     * @param pkDimissionId 离职流程模型
     * @param request 服务器请求 用于得到登陆人信息
     * @return
     */
    @UserLoginToken
    @PostMapping("sectionNoPass")
    public int sectionNoPass(@RequestParam("pkDimissionId") Long pkDimissionId,HttpServletRequest request,@RequestParam("departmentLeadership") String departmentLeadership){
        rowMap(request);
        try{
            return dimissionFlowService.sectionNoPass(pkDimissionId,personnel,departmentLeadership);
        }catch (Exception e){
            addErrorLog(request,"部门领导不通过",e);
            return 500;
        }
    }

    /**
     * 人事通过
     * @param departmentLeadership 离职流程模型
     * @param request 服务器请求 用于得到登陆人信息
     * @return
     */
    @UserLoginToken
    @PostMapping("staffingPass")
    public int staffingPass(@RequestParam("departmentLeadership") String departmentLeadership,HttpServletRequest request,@RequestParam("pkDimissionId") Long pkDimissionId){
        rowMap(request);
        try{
            return dimissionFlowService.staffingPass(pkDimissionId,personnel,departmentLeadership);
        }catch (Exception e){
            addErrorLog(request,"人事通过",e);
            return 500;
        }

    }

    /**
     * 人事不通过
     * @param pkDimissionId 离职流程模型
     * @param departmentLeadership 不通过的原因
     * @param request 服务器请求 用于得到登陆人信息
     * @return 增加的行数
     */
    @UserLoginToken
    @PostMapping("staffingNoPass")
    public int staffingNoPass(@RequestParam("departmentLeadership") String departmentLeadership,HttpServletRequest request,@RequestParam("pkDimissionId") Long pkDimissionId){
        rowMap(request);
        try{
            return dimissionFlowService.staffingNoPass(pkDimissionId,personnel,departmentLeadership);
        }catch (Exception e){
            addErrorLog(request,"人事不通过",e);
            return 500;
        }

    }

    /**
     *
     * @param id 离职流程id
     * {
     *      id:1111
     * }
     * @param request 服务器请求 用于得到登录人信息
     * @return 离职流程模型
     * {
     *     pkDimissionId : 111,
     *     demissionName : 离职名称
     * }
     */
    @UserLoginToken
    @GetMapping("findById/{id}")
    public OaDimissionFlow findById(@PathVariable("id") Long id,HttpServletRequest request){
        rowMap(request);
        try{
           return dimissionFlowService.findById(id);
        }catch (Exception e){
            addErrorLog(request,"人员离职id查询",e);
        }
        return null;
    }

    /**
     * id删除
     * @param id 离职流程id
     * @param request 服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @DeleteMapping("deleteById/{id}")
    public Map<String,Object> deleteById(@PathVariable("id") Long id, HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            OaDimissionFlow dimissionFlow=dimissionFlowService.findById(id);
            row=dimissionFlowService.delete(id);
            log.setLogTitle("人员离职删除");
            log.setLogBody(JSON.toJSON(dimissionFlow).toString());
            log.setLogType("1");
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"人员离职删除",e);
        }

        return map;
    }

    /**
     * 查询是否已经提交离职申请
     * @param request
     * @return
     */
    @UserLoginToken
    @GetMapping("getDimissionFlow")
    public int getDimissionFlow(HttpServletRequest request){
        OaPersonnel personnel=(OaPersonnel)request.getSession().getAttribute("user");
        return dimissionFlowService.getDimissionFlow(personnel.getPkPersonnelId());
    }

    /**
     * 查询报错日志新增
     * @param request 请求 用于得到当前登录人和ip地址
     * @param title 模块标题
     * @param e 异常参数
     */
    private void addErrorLog(HttpServletRequest request,String title,Exception e){
        e.printStackTrace();
        rowMap(request);
        log.setLogType("0");
        log.setLogBody(e.getLocalizedMessage());
        log.setLogTitle(title);
        if(ObjectUtils.isEmpty(personnel)){
            log.setCreatedBy(personnel.getPersonnelName());
        }
        tools.errorMap(log);
    }

    /**
     * 简化代码
     * @param request 服务器请求
     */
    private void rowMap(HttpServletRequest request){
        //新建返回Map模型
        map=new HashMap<>(16);
        //获取登陆人信息
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        //为空则清空map
        if(ObjectUtils.isEmpty(personnel)){
            return;
        }
        //新建日志
        log=new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(personnel.getPersonnelName());
    }

    /**
     * 日期格式化
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // true:允许输入空值，false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
